package com.rjj.wlqq.importExcel;

import com.jfinal.kit.PathKit;
import com.rjj.wlqq.tool.io.FileKit;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 需要测试
 *
 * 导入数据，因为数据比较多，所以，用进度条显示导入的进度
 */
@Controller
@RequestMapping("/important")
public class ImportantExcelController {
    private static Logger log = LoggerFactory.getLogger(ImportantExcelController.class);


    //资源加载器
    @Resource
    private ResourceLoader resourceLoader;

    /**
     * 导入页面
     */
    @RequestMapping("importantExcel")
    public String importantExcel() {
        return "/importExcel/excelImport";
    }


    /**
     * 导入实现
     * getFile("fileField"), getPara("actid")
     * <p>
     * 进度条是使用前端的定时器实现的
     */
    @RequestMapping("importantPart")
    @ResponseBody
    public Map<String, Object> importantPart(HttpServletRequest request, HttpServletResponse response, @RequestParam("file") MultipartFile file) {

        return importantExcel(file);
    }

    /**
     * 导入的操作
     * 这个可以放到service中
     * @param file 上传的文件
     */
    private Map<String, Object> importantExcel(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();//文件名称
        log.info("拿到的文件的名称为：" + originalFilename);

        //如果保存文件就把文件输出到指定的目录下就可以了,这里的路径需要绝对路径
		/*String filePath = "/Users/xx/workspace/temp/";
		File dest = new File(filePath + originalFilename);
		try {
			file.transferTo(dest);
			log.info("上传成功");
		} catch (IOException e) {
			log.info("上传失败");
		}*/

        //进度条的key，这里的key应该返回前台，这个唯一性更强
        String key = "xx";

        String suffix = originalFilename.substring(originalFilename.length() - 4);
        if (!".xls".equals(suffix)) {
            log.info("请选择后缀名为 .xls的Excel文件！");
        }

        Progress progress = new Progress();
        //导入信息表
        Map<String, Object> record = ImportRecordService.ME.insertImportRecord("存储需要保存的数据,就是一个记录数据的，记录在数据库中，谁在什么时间导入了一个excel，上传到哪里了");
        // 处理导入数据,存入数据库
        ImportXls importXls = ImportantService.IMPORTANT_SERVICE.getImport();
        //处理的结果，成功失败总共条数
        Map<String, Object> kv = importXls.save(file, "tableName", record, progress, key);
        //处理数据的日志
        StringBuilder msgs = importXls.getMsgs();
        // 返回结果
        Map<String, Object> map = new HashMap<>();
        map.put("record", record);
        map.put("kv", kv);
        map.put("msg", "".equals(msgs.toString()) ? "成功" : msgs.toString());
        return map;
    }

    /**
     * 删除生成的excel
     * 错误日志excel
     */
    @RequestMapping("deleteExcel")
    @ResponseBody
    public boolean deleteExcel(@RequestParam("url") String url) {
        File file = new File(PathKit.getWebRootPath() + url);
        boolean delete = false;
        if (file.exists()) {
            delete = file.delete();
        }
        return delete;
    }

    /**
     * 可以做前端进度条
     * url:/activity/progress
     */
    @RequestMapping("progress")
    @ResponseBody
    public Object progress(@RequestParam("key") String key) {
        Progress progress = new Progress();
        return progress.get(Progress.PROGRESS_ + key);
    }

    /**
     * 模版下载
     * @param response 响应
     * @param request 请求
     */
    @ApiOperation("下载模板")
    @GetMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response, HttpServletRequest request) {
        InputStream inputStream = null;
        ServletOutputStream servletOutputStream = null;
        try {
            String filename = "外包人员信息导入模板.xls";
            String path = "templates/importExcel/aa.xls";
            org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:" + path);

            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            response.addHeader("charset", "utf-8");
            response.addHeader("Pragma", "no-cache");
            String encodeName = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString());
            response.setHeader("Content-Disposition", "attachment; filename=\"" + encodeName + "\";");

            inputStream = resource.getInputStream();
            servletOutputStream = response.getOutputStream();
            IOUtils.copy(inputStream, servletOutputStream);
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (servletOutputStream != null) {
                    servletOutputStream.close();
                    servletOutputStream = null;
                }
                if (inputStream != null) {
                    inputStream.close();
                    inputStream = null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @GetMapping("/download/errorExcel/{fileName}")
    public void download(HttpServletRequest request, HttpServletResponse response, @PathVariable("fileName") String fileName){
        try {
            fileName = ResourceUtils.getURL("download").getPath() +"errorExcel/" +  fileName;
            System.out.println(fileName+"+++++++++++++++++" + ResourceUtils.getURL(ResourceUtils.CLASSPATH_URL_PREFIX).getPath()+ "    " + PathKit.getWebRootPath());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            FileKit.downloadResponse(fileName,request,response);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }



    /**
     * 下载样表String filePath, String fileName, String newName
     *  测试
     */
    @GetMapping("/downTemplet1")
    public static ResponseEntity<InputStreamResource> download() {

        ResponseEntity<InputStreamResource> response = null;
        try {
            String path = "/templates/importExcel/aa.xls";
            ClassPathResource classPathResource = new ClassPathResource(path);
            InputStream inputStream = classPathResource.getInputStream();
            //File file = new File(path);

            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition",
                    "attachment; filename="
                            + new String("aaa".getBytes("gbk"), "iso8859-1") + ".xls");
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            response = ResponseEntity.ok().headers(headers)
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(new InputStreamResource(inputStream));
        } catch (FileNotFoundException e1) {
            log.error("找不到指定的文件", e1);
        } catch (IOException e) {
            log.error("获取不到文件流", e);
        }
        return response;
    }

}
